package com.wiz.web.controllor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wiz.entity.Resources;
import com.wiz.entity.UserLoginList;
import com.wiz.service.ResourcesService;
import com.wiz.service.UserLoginListService;
import com.wiz.service.UserService;
import com.wiz.util.Common;
import com.wiz.web.UserTracker;

@Controller
@RequestMapping("/admin")
public class AdminControllor {
	@Resource
	private UserService userService;
	@Resource
	private ResourcesService resourcesService;
	@Resource
	private UserLoginListService userLoginListService;
	@Autowired
	private AuthenticationManager myAuthenticationManager;

	@RequestMapping(value="/login")
	public String login(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password,
			HttpSession session, Model model){
		try {
			if (!request.getMethod().equals("POST")) {
				request.setAttribute("error","支持POST方法提交！");
			}
			if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
				request.setAttribute("error","用户名或密码不能为空！");
				return "login";
			}
			// 验证用户账号与密码是否正确
			com.wiz.entity.User users = this.userService.querySingleUser(username);
			if (users == null || !users.getPassword().equals(password)) {
				request.setAttribute("error", "用户或密码不正确！");
			    return "login";
			}
			UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,password);
			Authentication authentication = myAuthenticationManager
					.authenticate(usernamePasswordAuthenticationToken);
			SecurityContext securityContext = SecurityContextHolder.getContext();
			securityContext.setAuthentication(authentication);
			
		    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);  
		    // 当验证都通过后，把用户信息放在session里
			request.getSession().setAttribute("userSession", users);
//			// 记录登录信息
//			UserLoginList userLoginList = new UserLoginList();
//			userLoginList.setUserId(users.getId());
//			userLoginList.setLoginIp(Common.toIpAddr(request));
//			userLoginListService.add(userLoginList);
		} catch (AuthenticationException e) {  
			e.printStackTrace();
			request.setAttribute("error", "登录异常，请联系管理员！");
		    return "login";
		}
		return "redirect:/admin/toIndex";
	}
	@RequestMapping ("toIndex")
	public String toIndex(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model){
		try {
//			UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

//			String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			String username = request.getUserPrincipal().getName();
			List<Resources> resources = resourcesService.listmenusByUserName(username);//getResourcesByUserName(username);
			System.out.println(resources.size());
			model.addAttribute("resources", resources);
		} catch (Exception e) {
			e.printStackTrace();
			//重新登录时销毁该用户的Session
			request.getSession().removeAttribute("SPRING_SECURITY_CONTEXT");
			return "redirect:/admin/login";
		}
		return "index";
	}
	
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password,
			HttpSession session, Model model){
		UserTracker.removeUser(request);
		return "login";
	}
	
}
